import {useNavigate, useParams} from "react-router-dom"
import React, { useContext, useEffect, useState, useCallback } from "react";
import Spinner from "../components/Spinner";
import { UserContext } from "../context/userContext";
import {Card, Switch, Button, Grid, Space, Avatar, Modal, Result, NavBar, Rate, Dialog, Selector} from 'antd-mobile'
import axios from "axios";
import PostItem from "../components/PostItem";
import PostApply from "../components/PostApply";

// 项目详情
const PostDetails = () => {
  // 获取路由参数：项目id
  const {id} = useParams()
  // 下面这些参数从服务端获取的，更新到页面显示
  const [post, setPost] = useState(null);
  const [applies, setApplies] = useState([]);
  const [name, setName] = useState('');
  const [avatar, setAvatar] = useState('');
  const [stars, setStars] = useState('4.5');
  const [status, setStatus] = useState('init');
  const [error, setError] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  // 获取上下文中的当前登录用户
  const { currentUser } = useContext(UserContext);
  const token = currentUser?.token;
  const userId = currentUser?.id;
  // 用于跳转到其它页面，比如返回=navigate(-1)
  const navigate = useNavigate()
  const back = () =>{
    navigate(-1);
  }
  // 申请加入项目按钮调用服务端接口
  const apply =  async () => {
    try {
      // await=等待请求结果 axios.post=axios网络请求组件发起post请求：
      // 第一个参数是 url，第二个参数是 data=数据可以为空{}，第三个是 header 请求头信息。
      const response = await axios.post(
          `${process.env.REACT_APP_BASE_URL}/posts/apply/${post._id}`,{},
          { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
      );
      // 如果返回值状态是200代表正常返回
      if (response.status === 200) {
        setStatus('applied')
        // 使用Modal组件弹个对话框
        await Modal.alert({
          content: <Result status="success"
                           title="申请成功"
                           description="我们正在审核报名信息，审核结果将会尽快通知您，请关注邮件或站内通知"/>,
          onConfirm: () => {
            console.log('Confirmed')
          },
        });
      }
    } catch (err) {
      setError(err.response.data.message);
    }
  };

  // 同意
  const agreeApply = async (id) => {
    setIsLoading(true)
    try {
      const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/posts/agreeApply/${id}`)
      console.log(response?.status)
    } catch (err) {
      console.log(err);
    }
    setIsLoading(false)
  }

  // 拒绝
  const rejectApply = async (id) => {
    setIsLoading(true)
    try {
      const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/posts/rejectApply/${id}`)
      console.log(response?.status)
    } catch (err) {
      console.log(err);
    }

    setIsLoading(false)
  }

  useEffect(() => {
    // 从服务端获取一个项目详情
    const getPost = async () => {
      // 显示加载中
      setIsLoading(true);
      try {
        // 发送 get 请求：await axios.get，这个可以不需要 header 参数。
        const response = await axios.get(`${process.env.REACT_APP_BASE_URL}/posts/${id}`)
        setPost(response.data)
        // 获取项目方创建者的用户信息，这里就需要headers参数（token 来自登录成功的返回值，它保存在客户端本地，它是会过期的）
        const response2 = await axios.get(
            `${process.env.REACT_APP_BASE_URL}/users/${response.data['creator']}`,
            { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
        );
        const { name, avatar, credits:stars} = response2.data;
        setStars(stars?stars:0.0)
        setName(name);
        setAvatar(avatar);
        // 请求服务端获取申请人列表
        const response3 = await axios.get(`${process.env.REACT_APP_BASE_URL}/posts/applies/${id}`)
        setApplies(response3?.data);
        // 请求服务端查看当前用户的申请状态，status 有几个状态=applied、approved、failed，分别是已申请、同意、拒绝，项目关闭的时候都会显示 closed。
        const response4 = await axios.get(`${process.env.REACT_APP_BASE_URL}/posts/applied/${id}`, { withCredentials: true, headers: { Authorization: `Bearer ${token}` }})
        const { status } = response4?.data;
        setStatus(status);
      } catch (error) {
        setError(error);
      }
      // 隐藏加载中图标，正常展示页面
      setIsLoading(false)
    }

    getPost()
  }, [])

  if (isLoading) {
    return <Spinner />
  }

  return (
      <section className="post-details">
        <NavBar style={{'background-color': 'rgba(80, 62, 157, 1)', 'color': 'white'}} onBack={back}>项目详情</NavBar>

        <div className="header">
          <Space block direction='horizontal' align="center">
            <Avatar style={{'--size': '64px'}} src={`${process.env.REACT_APP_ASSETS_URL}/uploads/${avatar}`} alt=""/>
            <Space block direction='vertical'>
              <Space block>
                <span className="text_3">{name}</span> <span className="text_5">创建者</span>
              </Space>
              <Space>
                <span className="text_4">当前评分: <Rate style={{'--star-size':'15px'}} value={Number(stars)} readOnly/></span>
              </Space>
            </Space>
          </Space>

        </div>
        <div className="part">
          {post && <PostItem postID={post._id}
                             createdAt={post.createdAt}
                             views={post.views}
                             applies={post.applies}
                             wages={post.wages}
                             title={post.title}
                             authorID={post.creator}/>}
        </div>
        <div className="part">
          {post && <Card title='需求详情'>
            {post.description}
          </Card>}
        </div>
        <div className="part">
          {post && <Card title='参与成员'>
            <Grid columns={4} gap={8}>
              {applies.map(value => {
                return (<Grid.Item key={value._id}>
                  {/*审批选择：第一次勾选=同意，取消勾选=拒绝*/}
                  <Selector
                      options={[
                        {
                          label: <PostApply authorID={value.userId}/>,
                          description: userId !== post.creator?'':(value.status === 'approved'?'已同意':(value.status === 'failed'?'已拒绝':'待审核...')),
                          value: value.userId,
                        }
                      ]}
                      value={[value.status === 'approved'?value.userId:undefined]}
                      onChange={async (arr, extend) => {
                        console.log(arr, value._id)
                        if(userId !== post.creator) {
                          console.log('不是项目方，不能操作审批');
                          return;
                        }
                        if (arr.length) {
                          value.status = 'approved';
                          await agreeApply(value._id);
                          let all = [...applies]
                          setApplies(all);
                        } else {
                          value.status = 'failed';
                          await rejectApply(value._id);
                          let all = [...applies]
                          setApplies(all);
                        }
                      }}
                  />
                </Grid.Item>)
              })}

            </Grid>
          </Card>}

        </div>
        {error && <p className="error text_4">{error}</p>}
        {post && post.creator !== userId && <Card>
          {status === 'init' && <Button onClick={apply} block style={{
            "--background-color": 'rgba(80, 62, 157, 1)',
            "--text-color": 'rgba(255, 255, 255, 1)',
            "--border-radius": '12px'
          }} size='large'>申请加入</Button>}
          {status === 'approved' && <Button onClick={()=> {
            Dialog.alert({
              title:'查看联系方式',
              content: '您的申请已通过审核，项目联系方式：' + (post.agree?post.contact:post.email),
              closeOnMaskClick: true,
            })
          }} block style={{
            "--background-color": 'rgba(80, 62, 157, 1)',
            "--text-color": 'rgba(255, 255, 255, 1)',
            "--border-radius": '12px'
          }} size='large'>查看联系方式</Button>}
          {status === 'applied' && <Button disabled={true} block style={{
            "--background-color": 'rgba(251, 110, 58, 0.11)',
            "--text-color": 'rgba(251, 110, 58, 1)',
            "--border-radius": '12px'
          }} size='large'>审核中...</Button>}
          {status === 'failed' && <Button disabled={true} block style={{
            "--background-color": 'rgba(255, 0, 0, 0.11)',
            "--text-color": 'rgba(255, 0, 0, 1)',
            "--border-radius": '12px'
          }} size='large'>申请失败</Button>}
          {status === 'closed' && <Button disabled={true} block style={{
            "--background-color": 'rgba(255, 0, 0, 0.11)',
            "--text-color": 'rgba(255, 0, 0, 1)',
            "--border-radius": '12px'
          }} size='large'>已关闭</Button>}
        </Card>}
      </section>
  );
}

export default PostDetails
